/**
 * 可读性分析面板组件
 * 显示阅读难度、句子分析、复杂词汇等
 */

import React from 'react';
import { Card, Progress, Row, Col, Statistic, List, Tag, Space, Table, Tooltip } from 'antd';
import {
  ReadOutlined,
  LineChartOutlined,
  FileTextOutlined,
  CheckCircleOutlined,
  WarningOutlined,
} from '@ant-design/icons';
import type { ReadabilityAnalysis } from '@/stores/optimizer.store';
import './style.css';

interface ReadabilityPanelProps {
  analysis: ReadabilityAnalysis;
  onReplaceWord?: (word: string, replacement: string) => void;
}

/**
 * 获取阅读难度等级
 */
const getReadingLevelText = (level: number): string => {
  if (level <= 3) return '小学';
  if (level <= 6) return '初中';
  if (level <= 9) return '高中';
  return '大学';
};

/**
 * 获取阅读难度颜色
 */
const getReadingLevelColor = (level: number): string => {
  if (level <= 6) return '#52c41a';  // 易读
  if (level <= 8) return '#faad14';  // 中等
  return '#ff4d4f';                  // 困难
};

/**
 * 获取Flesch评分等级
 */
const getFleschGrade = (score: number): string => {
  if (score >= 80) return '非常易读';
  if (score >= 60) return '易读';
  if (score >= 50) return '较易读';
  if (score >= 30) return '较难读';
  return '难读';
};

/**
 * 获取目标读者文本
 */
const getTargetAudienceText = (audience: ReadabilityAnalysis['targetAudience']): string => {
  const map = {
    general: '大众读者',
    professional: '专业人士',
    expert: '领域专家',
  };
  return map[audience];
};

export const ReadabilityPanel: React.FC<ReadabilityPanelProps> = ({
  analysis,
  onReplaceWord,
}) => {
  // 复杂词汇表格列
  const complexWordColumns = [
    {
      title: '复杂词汇',
      dataIndex: 'word',
      key: 'word',
      render: (text: string) => <Tag color="orange">{text}</Tag>,
    },
    {
      title: '位置',
      dataIndex: 'position',
      key: 'position',
      width: 100,
    },
    {
      title: '建议替换',
      dataIndex: 'simpler',
      key: 'simpler',
      render: (simpler: string[], record: any) => (
        <Space>
          {simpler.map((word) => (
            <Tag
              key={word}
              color="green"
              style={{ cursor: onReplaceWord ? 'pointer' : 'default' }}
              onClick={() => onReplaceWord && onReplaceWord(record.word, word)}
            >
              {word}
            </Tag>
          ))}
        </Space>
      ),
    },
  ];

  return (
    <div className="readability-panel">
      {/* 阅读难度总览 */}
      <Row gutter={16}>
        <Col span={8}>
          <Card>
            <Statistic
              title="阅读难度等级"
              value={analysis.readingLevel}
              suffix={`级 (${getReadingLevelText(analysis.readingLevel)})`}
              valueStyle={{ color: getReadingLevelColor(analysis.readingLevel) }}
              prefix={<ReadOutlined />}
            />
          </Card>
        </Col>

        <Col span={8}>
          <Card>
            <Statistic
              title="Flesch可读性"
              value={analysis.fleschScore}
              suffix="分"
              valueStyle={{ color: analysis.fleschScore >= 60 ? '#52c41a' : '#faad14' }}
              prefix={<LineChartOutlined />}
            />
            <div style={{ marginTop: 8, fontSize: 12, color: '#8c8c8c' }}>
              {getFleschGrade(analysis.fleschScore)}
            </div>
          </Card>
        </Col>

        <Col span={8}>
          <Card>
            <Statistic
              title="目标读者"
              value={getTargetAudienceText(analysis.targetAudience)}
              prefix={<FileTextOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 句子和段落统计 */}
      <Card title="句子与段落分析" size="small" style={{ marginTop: 16 }}>
        <Row gutter={16}>
          <Col span={12}>
            <div className="stat-item">
              <div className="stat-label">平均句子长度</div>
              <div className="stat-value">
                {analysis.avgSentenceLength.toFixed(1)} 字
              </div>
              <Progress
                percent={Math.min(100, (analysis.avgSentenceLength / 30) * 100)}
                strokeColor={
                  analysis.avgSentenceLength <= 20
                    ? '#52c41a'
                    : analysis.avgSentenceLength <= 25
                    ? '#faad14'
                    : '#ff4d4f'
                }
                showInfo={false}
              />
              <div className="stat-hint">
                {analysis.avgSentenceLength <= 20
                  ? '✓ 句子长度适中'
                  : '! 建议缩短句子'}
              </div>
            </div>
          </Col>

          <Col span={12}>
            <div className="stat-item">
              <div className="stat-label">平均段落长度</div>
              <div className="stat-value">
                {analysis.avgParagraphLength.toFixed(0)} 字
              </div>
              <Progress
                percent={Math.min(100, (analysis.avgParagraphLength / 150) * 100)}
                strokeColor={
                  analysis.avgParagraphLength <= 100
                    ? '#52c41a'
                    : analysis.avgParagraphLength <= 120
                    ? '#faad14'
                    : '#ff4d4f'
                }
                showInfo={false}
              />
              <div className="stat-hint">
                {analysis.avgParagraphLength <= 100
                  ? '✓ 段落长度适中'
                  : '! 建议拆分段落'}
              </div>
            </div>
          </Col>
        </Row>
      </Card>

      {/* 句子长度分布 */}
      <Card title="句子长度分布" size="small" style={{ marginTop: 16 }}>
        <Row gutter={16}>
          <Col span={8}>
            <div className="distribution-item">
              <div className="distribution-label">
                <CheckCircleOutlined style={{ color: '#52c41a' }} /> 短句 (&lt; 15字)
              </div>
              <Progress
                percent={(analysis.sentenceLengthDistribution.short /
                  (analysis.sentenceLengthDistribution.short +
                   analysis.sentenceLengthDistribution.medium +
                   analysis.sentenceLengthDistribution.long)) * 100}
                strokeColor="#52c41a"
              />
              <div className="distribution-count">
                {analysis.sentenceLengthDistribution.short} 句
              </div>
            </div>
          </Col>

          <Col span={8}>
            <div className="distribution-item">
              <div className="distribution-label">
                <CheckCircleOutlined style={{ color: '#faad14' }} /> 中句 (15-25字)
              </div>
              <Progress
                percent={(analysis.sentenceLengthDistribution.medium /
                  (analysis.sentenceLengthDistribution.short +
                   analysis.sentenceLengthDistribution.medium +
                   analysis.sentenceLengthDistribution.long)) * 100}
                strokeColor="#faad14"
              />
              <div className="distribution-count">
                {analysis.sentenceLengthDistribution.medium} 句
              </div>
            </div>
          </Col>

          <Col span={8}>
            <div className="distribution-item">
              <div className="distribution-label">
                <WarningOutlined style={{ color: '#ff4d4f' }} /> 长句 (&gt; 25字)
              </div>
              <Progress
                percent={(analysis.sentenceLengthDistribution.long /
                  (analysis.sentenceLengthDistribution.short +
                   analysis.sentenceLengthDistribution.medium +
                   analysis.sentenceLengthDistribution.long)) * 100}
                strokeColor="#ff4d4f"
              />
              <div className="distribution-count">
                {analysis.sentenceLengthDistribution.long} 句
              </div>
            </div>
          </Col>
        </Row>

        <div className="distribution-recommendation">
          <strong>建议比例：</strong> 短句 30-40%，中句 40-50%，长句 10-20%
        </div>
      </Card>

      {/* 语态分析 */}
      <Row gutter={16} style={{ marginTop: 16 }}>
        <Col span={12}>
          <Card size="small">
            <Statistic
              title="被动语态数量"
              value={analysis.passiveVoiceCount}
              suffix="处"
              valueStyle={{ color: analysis.passiveVoiceCount > 5 ? '#faad14' : '#52c41a' }}
            />
            {analysis.passiveVoiceCount > 5 && (
              <div className="stat-warning">
                <WarningOutlined style={{ color: '#faad14', marginRight: 4 }} />
                建议减少被动语态，改用主动语态
              </div>
            )}
          </Card>
        </Col>

        <Col span={12}>
          <Card size="small">
            <Statistic
              title="过渡词数量"
              value={analysis.transitionWords}
              suffix="个"
              valueStyle={{ color: analysis.transitionWords >= 5 ? '#52c41a' : '#faad14' }}
            />
            {analysis.transitionWords < 5 && (
              <div className="stat-warning">
                <WarningOutlined style={{ color: '#faad14', marginRight: 4 }} />
                建议增加过渡词，提升连贯性
              </div>
            )}
          </Card>
        </Col>
      </Row>

      {/* 复杂词汇 */}
      {analysis.complexWords.length > 0 && (
        <Card title="复杂词汇建议" size="small" style={{ marginTop: 16 }}>
          <Table
            dataSource={analysis.complexWords}
            columns={complexWordColumns}
            rowKey="word"
            size="small"
            pagination={{ pageSize: 5 }}
          />
        </Card>
      )}

      {/* 改进建议 */}
      <Card title="可读性改进建议" size="small" style={{ marginTop: 16 }}>
        <List
          size="small"
          dataSource={analysis.improvements}
          renderItem={(item, index) => (
            <List.Item>
              <Space>
                <span className="improvement-number">{index + 1}.</span>
                <span>{item}</span>
              </Space>
            </List.Item>
          )}
        />
      </Card>
    </div>
  );
};
